﻿using TCC.Framework;
using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditor.ProjectWindowCallback;
using System.Text;
using System;

namespace TCC.Framework
{
    public class CreateScriptFromTemplate
    {
        public static void Create(Type type, string templatePath, string destName, Texture2D icon)
        {
            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(
                0,
                ScriptableObject.CreateInstance(type) as EndNameEditAction,
                destName,
                icon,
                templatePath
                );
        }

        public static void Create<T>(string templatePath, string destName, Texture2D icon) where T : DoCreateScriptAsset
        {
            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(
                0,
                ScriptableObject.CreateInstance<T>(),
                destName,
                icon,
                templatePath
                );
        }
    }
    public abstract class DoCreateScriptAsset : EndNameEditAction
    {
        public virtual string Suffix { get; set; } = ".cs";

        public override void Action(int instanceId, string pathName, string resourceFile)
        {
            UnityEngine.Object obj = CreateAssetFromTemplate(pathName, resourceFile);
            ProjectWindowUtil.ShowCreatedAsset(obj);
        }

        internal UnityEngine.Object CreateAssetFromTemplate(string pathName, string resourceFile)
        {
            string className = pathName.Remove(0, pathName.LastIndexOf('/') + 1);
            pathName += Suffix;
            string fullName = Path.GetFullPath(pathName);
            StreamReader reader = new StreamReader(resourceFile);
            string content = reader.ReadToEnd();
            reader.Close();

            content = ReplaceTemplateContent(className, content);
            
            StreamWriter writer = new StreamWriter(fullName, false, UTF8Encoding.UTF8);
            writer.Write(content);
            writer.Close();

            AssetDatabase.ImportAsset(pathName);
            AssetDatabase.Refresh();
            return AssetDatabase.LoadMainAssetAtPath(pathName);
        }

        /// <summary>
        /// 替换模版内容
        /// </summary>
        /// <param name="templateContent">替换内容</param>
        /// <returns></returns>
        public abstract string ReplaceTemplateContent(string className, string templateContent);
    }
}


